define([
    'app',
    'json5',
    'rtext!views/pages/templates/regexp-debugger.list.json',
    'rtext!views/pages/templates/regexp-debugger.meta.json5'
], function(app, JSON5, regexps, metachars) {
    app.controller('RegExpDebuggerController', function($scope, $compile, xUtil) {
        var self = this;
        self.regexps = [];
        self.metachars = [];

        self.text = '';
        self.regexp = '';
        self.global = false;
        self.caseIgnored = false;
        self.swap = '';
        self.match = '';
        self.replace = '';

        self.init = function() {
            xUtil.clipboard.copy('#copy', function() {
                return self.regexp;
            });

            var objRegexps = JSON.parse(regexps);
            encodeHtml(objRegexps);
            self.regexps = objRegexps;

            var objMetachars = JSON5.parse(metachars);
            encodeHtml(objMetachars, function(metachar, name, value) {
                metachar[name] = metachar[name].split('\n').join('<br>');
            });
            self.metachars = objMetachars;
        }

        const htmlChars = { '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' };
        function encodeHtml(json, callback) {
            _.forEach(json, function(object) {
                _.forEach(object, function(value, name) {
                    object[name] = object[name].replace(/[<>&"]/g, function(char) {
                        return htmlChars[char];
                    });
                    if (callback) {
                        callback(object, name, value);
                    }
                });
            });
        }

        self.debug = function(valid, method) {
            if (valid) {
                var objRegExp = new RegExp(self.regexp, [self.global ? 'g' : '',
                        self.caseIgnored ? 'i' : ''].join(''));
                if (method == 'match') {
                    var match = self.text.match(objRegExp);
                    if (_.isEmpty(match)) {
                        self.match = '（没有匹配）';
                    } else if (self.global) {
                        var result = ['共找到 ' + match.length + ' 处匹配：'];
                        _.forEach(match, function(item) {
                            result.push(item);
                        });
                        self.match = result.join('\n');
                    } else {
                        self.match = [
                            '匹配位置：' + objRegExp.lastIndex,
                            '匹配结果：' + match[0]
                        ].join('\n');
                    }
                } else {
                    self.replace = self.text.replace(objRegExp, self.swap);
                }
            }
        }

        self.callback = function(height, width, refresh) {
            $('.x-view-scope .tab-pane').css('height', (height - 57) + 'px');
            // Toolbar
            if (refresh) {
                $('.navbar-form').append($compile($('#opt-toolbar').html())($scope));
            }
        }

        self.reset = function() {
            self.text = '';
            self.regexp = '';
            self.global = false;
            self.caseIgnored = false;
            self.swap = '';
            self.match = '';
            self.replace = '';
        }
    });
});
